// main.dart
import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:get/get.dart';
import 'package:thingskit/apiService/mode.dart';
import 'package:thingskit/components/constantButton.dart';
import '../../components/aRowBottons.dart';
import '../../components/functionButton.dart';
import '../../components/showModeDescription.dart';
import '../../components/singleRowCard.dart';
import '../../utils/ToastController.dart';

class ModeManagemenController extends GetxController {
  RxList<Mode> modes = <Mode>[].obs;
  var selectedModeId = 0.obs;
  final TextEditingController nameController = TextEditingController();
  final ToastController toastController = Get.find();

  @override
  void onInit() {
    getModes();
    super.onInit();
  }

  //获取方案列表
  Future<void> getModes() async {
    EasyLoading.show(status: '加载中...', maskType: EasyLoadingMaskType.black);
    try {
      modes.value = await ModeApi().getModeList();
    } catch (e) {
      EasyLoading.showError('加载失败');
    } finally {
      EasyLoading.dismiss();
    }
  }

  // 删除方案
  Future<void> deleteMode() async {
    if (selectedModeId.value == 0) {
      return;
    }
    try {
      await ModeApi().deleteMode(selectedModeId.value);
      EasyLoading.showSuccess('删除成功');
      getModes();
    } catch (e) {
      EasyLoading.showError('删除失败');
    } finally {
      EasyLoading.dismiss();
    }
  }

  // 修改方案名称
  Future<void> updateModeName(String name) async {
    if (selectedModeId.value == 0) {
      return;
    }
    try {
      await ModeApi().updateModeName(selectedModeId.value, name);
      EasyLoading.showSuccess('修改成功');
      getModes();
    } catch (e) {
      EasyLoading.showError('修改失败');
    } finally {
      EasyLoading.dismiss();
    }
  }

  // 查看方案
  void showModeDetail(Mode mode) {
    Get.dialog(
      SimpleDialog(
        backgroundColor: Colors.white,
        title: Center(
          child: Text('方案详情', style: TextStyle(fontWeight: FontWeight.bold)),
        ),
        shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)),
        contentPadding: EdgeInsets.symmetric(horizontal: 20, vertical: 5),
        children: [
          ConstrainedBox(
            constraints: BoxConstraints(
              maxWidth: Get.width * 0.8,
              maxHeight: Get.height * 0.8,
            ),
            child: Column(
              // 关键：收缩内容高度
              mainAxisSize: MainAxisSize.min,
              children: [
                SizedBox(height: 10),
                ShowModeDescription(mode: mode.content),
              ],
            ),
          ),
        ],
      ),
    );
  }

  // 显示修改名称弹窗
  void showUpdateModeNameDialog() {
    nameController.clear();
    if (selectedModeId.value == 0) {
      toastController.showCenterToast('请选择一个方案');
      return;
    }
    Get.dialog(
      AlertDialog(
        title: Text('修改方案名称'),
        content: TextField(
          controller: nameController,
          decoration: InputDecoration(hintText: '请输入方案名称'),
        ),
        actions: [
          TextButton(
            onPressed: () {
              Get.back();
            },
            child: Text('取消'),
          ),
          TextButton(
            onPressed: () {
              if (nameController.text.isEmpty) {
                toastController.showCenterToast('方案名称不能为空');
                return;
              }
              updateModeName(nameController.text);
              Get.back();
            },
            child: Text('确认'),
          ),
        ],
      ),
    );
  }

  // 显示删除方案弹窗
  void showDeleteModeDialog() {
    if (selectedModeId.value == 0) {
      toastController.showCenterToast('请选择一个方案');
      return;
    }
    Get.dialog(
      AlertDialog(
        title: Text('删除方案'),
        content: Text('确定要删除该方案吗？', style: TextStyle(fontSize: 16)),
        actions: [
          TextButton(
            onPressed: () {
              Get.back();
            },
            child: Text('取消'),
          ),
          TextButton(
            onPressed: () {
              deleteMode();
              Get.back();
            },
            child: Text('确认'),
          ),
        ],
      ),
    );
  }
}

class ModeManagementPage extends StatelessWidget {
  final ModeManagemenController controller = Get.put(ModeManagemenController());

  ModeManagementPage({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: AppBar(title: Text('方案管理')),
      body: Column(
        children: [
          Expanded(
            child: Obx(
              () =>
                  controller.modes.isEmpty
                      ? Center(child: Text('暂无数据'))
                      : ListView.builder(
                        itemCount: controller.modes.length,
                        itemBuilder: (context, index) {
                          final mode = controller.modes[index];
                          return Obx(
                            () => SingleRowCard(
                              content: Text(
                                mode.name,
                                maxLines: 1,
                                overflow: TextOverflow.ellipsis,
                                style: TextStyle(fontSize: 16),
                              ),
                              isChecked:
                                  controller.selectedModeId.value == mode.id,
                              onCheckChange: (newValue) {
                                controller.selectedModeId.value =
                                    newValue == true ? mode.id : 0;
                              },
                              onClick: () {
                                controller.showModeDetail(mode);
                              },
                            ),
                          );
                        },
                      ),
            ),
          ),
          Padding(
            padding: const EdgeInsets.all(16.0),
            child: ARowBottons(
              title1: '删除',
              color1: Colors.red,
              onPressed1: controller.showDeleteModeDialog,
              title2: '修改名称',
              color2: Colors.blue,
              onPressed2: controller.showUpdateModeNameDialog,
            ),
          ),
        ],
      ),
    );
  }
}
